package com.ev.k3cloudBusiness.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ev.common.enums.AuditStatusDict;
import com.ev.custom.dao.FacilityDao;
import com.ev.custom.domain.FacilityDO;
import com.ev.custom.service.FacilityService;
import com.ev.framework.utils.R;
import com.ev.framework.utils.ShiroUtils;
import com.ev.k3cloud.service.K3CloudService;
import com.ev.k3cloud.service.kingdeeMiddlewareService;
import com.ev.k3cloudBusiness.service.K3StockSynService;
import com.ev.k3cloudBusiness.vo.K3StockResultsVo;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class K3StockSynServiceImpl implements K3StockSynService {
    @Autowired
    FacilityDao facilityDao;
    @Autowired
    K3CloudService k3CloudService;
    @Autowired
    FacilityService facilityService;

    @Autowired
    private kingdeeMiddlewareService kingdeeMiddlewareService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R StockSyn() {
        //查询芯软云仓库
        List<FacilityDO> facilityDOList=facilityService.listAll();

        String stockResult = kingdeeMiddlewareService.StockAll();

        JSONObject resultObj = JSON.parseObject(stockResult);
        if (!resultObj.getString("code").equals("0")) {
            log.info(resultObj.getString("msg"));
            return R.error(resultObj.getString("msg"));
        }
        List<K3StockResultsVo> k3ClientResultsVOS = JSON
                .parseArray(resultObj.get("data").toString(), K3StockResultsVo.class);

        if(k3ClientResultsVOS.size() > 0)
        {
            long okAudit = AuditStatusDict.OK_AUDIT.getId();
            Long userId = ShiroUtils.getUserId();
            // 本地仓库代码
            List<Long> localIdList = facilityDOList.stream().map(FacilityDO::getId).collect(Collectors.toList());
            // K3Cloud仓库代码
            List<Long> remoteIdList = k3ClientResultsVOS.stream().map(K3StockResultsVo::getId).collect(Collectors.toList());
            // 删除的 k3无，本地有
            List<Long> deleteIdList = localIdList.stream().filter(e -> !remoteIdList.contains(e)).collect(Collectors.toList());
            // 修改的（本地库有的，远端库有的）
            List<Long> updateIdList = remoteIdList.stream().filter(localIdList::contains).collect(Collectors.toList());
            // 新增的（本地库无的，远端库有的）
            remoteIdList.removeAll(updateIdList);
            if(deleteIdList.size()>0)
            {
                //批量删除
                List<FacilityDO> facilityDOS=facilityDOList.stream().filter(e->deleteIdList.contains(e.getId())).collect(Collectors.toList());
                for (FacilityDO facilityDO:facilityDOS
                ) {
                    facilityDO.setDelFlag(1);
                }
                facilityService.batchUpdate(facilityDOS);
                log.info("批量删除");
            }
            if(updateIdList.size()>0)
            {
                //批量更新
                List<K3StockResultsVo> stockResulitsVos = k3ClientResultsVOS.stream().filter(e -> updateIdList.contains(e.getId())).collect(Collectors.toList());
                List<FacilityDO> facilityDOS=facilityDOList.stream().filter(e->updateIdList.contains(e.getId())).collect(Collectors.toList());
                K3StockResultsVo stockResulitsVo;
                for (FacilityDO facilityOne:facilityDOS
                ) {
                    stockResulitsVo=stockResulitsVos.stream().filter(e->(facilityOne.getId().equals(e.getId()))).collect(Collectors.toList()).get(0);
                    //仓库名称
                    facilityOne.setName(stockResulitsVo.getName());
                    //仓库代码
                    facilityOne.setSerialNo(stockResulitsVo.getNumber());
                    //组织代码
                    facilityOne.setOrgNumber(stockResulitsVo.getBrNO());
                    facilityOne.setAuditor(userId);
                }
                facilityService.batchUpdate(facilityDOS);
                log.info("批量更新");
            }
            if(remoteIdList.size()>0)
            {
                //批量插入
                List<K3StockResultsVo> stockResulitsVos= k3ClientResultsVOS.stream().filter(e -> remoteIdList.contains(e.getId())).collect(Collectors.toList());
                List<FacilityDO> facilityDOS= Lists.newArrayList();
                for (K3StockResultsVo stockResulitsVo:stockResulitsVos
                ) {
                    FacilityDO facilityDO=new FacilityDO();
                    facilityDO.setId(stockResulitsVo.getId());
                    //仓库姓名
                    facilityDO.setName(stockResulitsVo.getName());
                    //仓库代码
                    facilityDO.setSerialNo(stockResulitsVo.getNumber());
                    //组织代码
                    facilityDO.setOrgNumber(stockResulitsVo.getBrNO());
                    facilityDO.setDelFlag(0);
                    facilityDO.setAuditSign(okAudit);
                    facilityDO.setAuditor(userId);
                    facilityDOS.add(facilityDO);
                }
                facilityService.batchSave(facilityDOS);
                log.info("批量新增");
            }
        }
        return R.ok();
    }
}
